package com.funcourse.demo.business;

import com.funcourse.demo.model.Quiz;
import com.funcourse.demo.model.User;
import com.funcourse.demo.model.repo.QuestionSuitRepo;
import com.funcourse.demo.model.repo.UserRepo;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class UserService {
    @Autowired
    UserRepo userRepo;
    @Autowired
    QuestionSuitRepo questionSuitRepo;
    @Value("${quiz.default.owner}")
    String defaultQuizOwner;
    @Value("${user.default.avatar.url}")
    String defaultUserAvatarUrl;
    @Value("${user.auth.activation.code.default}")
    String defaulActiveCode;
    public Boolean avatarUrlCouldCover(String avatarUrl){
        if(StringUtils.isEmpty(avatarUrl)){
            return true;
        }
        return defaultUserAvatarUrl.equals(avatarUrl);
    }
    public User registerNewUser(){
        User user = new User();
        user.setAvatarUrl(defaultUserAvatarUrl);
        user.setToken(UUID.randomUUID().toString());
        user.setActivated(false);
        User userSaved = userRepo.save(user);
        assignDefaultQuizs(userSaved.getId());
        return userSaved;
    }

    public Boolean activeUser(User user,String activationCode){
        if(user.getActivated()){
            return true;
        }
        if(!defaulActiveCode.equals(activationCode)){
            return false;
        }
        user.setActivated(true);
        userRepo.save(user);
        return true;
    }

    private void assignDefaultQuizs(String userId){
        Page<Quiz> defaultQuizs = questionSuitRepo.findByOwnerId(defaultQuizOwner, PageRequest.of(0, 10));
        if(defaultQuizs.isEmpty()){
            log.warn("no default quiz found no default quiz is assigned to new user");
            return;
        }
        List<Quiz> collect = defaultQuizs.get().map(quiz -> {
            Quiz newQuiz = new Quiz();
            BeanUtils.copyProperties(quiz, newQuiz);
            newQuiz.setId(null);
            newQuiz.setOwnerId(userId);
            return newQuiz;
        }).collect(Collectors.toList());
        questionSuitRepo.insert(collect);
    }
}
